package com.zcsy.seller.web.report;

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.mall.OrderInfo;
import com.zcsy.manage.service.mall.IOrderInfoService;

/**
 * @Title: ReportController.java
 * @Package： com.zcsy.seller.web.coupon 
 * @Description: 报表控制层
 *
 * @author lilan 1063972142@qq.com
 * @Copyright: 2015 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年8月17日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "orderReport")
public class OrderStatisticsController {
	
	@Autowired
	private IOrderInfoService orderInfoService;
	
	/**
	 * 
	 * @Description 返回订单统计报表页面<br>
	 * 
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年8月17日
	 * @see
	 */
	@RequestMapping(value ="orderStatistics", method = RequestMethod.GET)
	public String orderStatistics(Model model) {
		
		return "report/orderStatistics";
	}
	
	/**
	 * 
	 * @Description 根据时间查询已完成和已取消的订单量，并生成双折线图<br>
	 * 
	 * @param days 查询时间间隔天数
	 * @param type 查询类型，1：固定搜索-一周、月度、季度、年度，2：自由搜索-自定义时间
	 * @param beginDate 开始时间
	 * @param endDate 结束时间
	 * @param req 用户请求
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年8月26日
	 * @see
	 */
	@RequestMapping(value="orderEchartsShow" , method = RequestMethod.POST)
	@ResponseBody
    public RequestJson orderEchartsShow(Integer days,Integer type,String beginDate,String endDate,HttpServletRequest req){
        RequestJson result = new RequestJson();
        ShopInfo shopInfo = (ShopInfo)req.getSession().getAttribute(RequestConstants.SHOP_ID);
        try {
        	List<OrderInfo> completedOrders = new ArrayList<OrderInfo>();
        	List<OrderInfo> canceledOrders = new ArrayList<OrderInfo>();
        	List<Object> list = new ArrayList<Object>();
        	Map<String, List<OrderInfo>> mapOne = new HashMap<>();
        	SimpleDateFormat sdf = DateUtils.yymd;
        	String[] xAix = new String[days];
        	String shopId = shopInfo.getId();
        	if(Constants.SEARCH_FIXED == type){
        		if(days <= 90 && days > 0){
        		completedOrders = orderInfoService.selectCompletedOrder(shopId);
        		canceledOrders = orderInfoService.selectCanceledOrder(shopId);

        		Date currentTime =DateUtils.str2Date(DateUtils.getCurrentTime(), sdf); // yyyy/MM/dd
        		Calendar rightNow = DateUtils.getCalendar();
        		xAix = getXAxis(currentTime,rightNow,sdf ,Calendar.DAY_OF_YEAR,xAix,days);
        		} 
        	} else if(Constants.SEARCH_FREE == type){
        		if(days <= 90 && days > 0){
        			completedOrders = orderInfoService.searchCompletedOrderByTime(beginDate, endDate,shopId);
        			canceledOrders = orderInfoService.searchCanceledOrderByTime(beginDate, endDate,shopId);
        			
        			Date endTime =DateUtils.str2Date(endDate, sdf); // yyyy/MM/dd
        			Calendar end = DateUtils.getCalendar();
        			xAix = getXAxis(endTime,end,sdf ,Calendar.DAY_OF_YEAR,xAix,days);
        			
        		}
        	}
                 
        		for(OrderInfo order:completedOrders){
        			String formatTime = sdf.format(order.getConfirmTime()); // yyyy/MM/dd

        			if(mapOne.containsKey(formatTime)){
        				mapOne.get(formatTime).add(order);
        			} else{
        				List<OrderInfo> templist = new ArrayList<OrderInfo>();
        				templist.add(order);
        				mapOne.put(formatTime, templist);
        			}
        		}

        		int[] yAix = getYAxis(mapOne,xAix,days);

        		Map<String, List<OrderInfo>> mapTwo = new HashMap<>();
        		for(OrderInfo order:canceledOrders){
        			String formatTime = sdf.format(order.getCancelTime()); // yyyy/MM/dd

        			if(mapTwo.containsKey(formatTime)){
        				mapTwo.get(formatTime).add(order);
        			} else{
        				List<OrderInfo> templist = new ArrayList<OrderInfo>();
        				templist.add(order);
        				mapTwo.put(formatTime, templist);
        			}
        		}

        		int[] yAixTwo = getYAxis(mapTwo,xAix,days);

        		Map mOne = new HashMap();
        		mOne.put(xAix, yAix);
        		Map mTwo = new HashMap();
        		mTwo.put(xAix, yAixTwo);

        		list.add(mOne.keySet());
        		list.add(mOne.values());
        		list.add(mTwo.values());
        		
        		result.setObj(list);
        		result.setSuccess(true);

        	} catch (Exception e) {
        		e.printStackTrace();
        		result.setSuccess(false);
        	}
        	return result;
    }
	
	/**
	 * 
	 * @Description 获取x坐标轴数据<br>
	 * 
	 * @param time 传入时间
	 * @param calendar 转换时间
	 * @param sdf 转换时间格式
	 * @param xAix x坐标对象
	 * @param days 开始时间和结束时间之差
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年8月26日
	 * @see
	 */
	private String[] getXAxis(Date time,Calendar calendar,SimpleDateFormat sdf ,Integer calenderType,String[] xAix,Integer days){
		calendar.setTime(time);
		calendar.add(calenderType, 1);
		for(int i = days-1; i >= 0; i--){
			calendar.add(calenderType, -1);
			Date dt1=calendar.getTime();
			String reStr = sdf.format(dt1);
			xAix[i] = reStr;
         }
		return xAix;
	}
	
	/**
	 * 
	 * @Description 获取y坐标数据<br>
	 * 
	 * @param m 存放订单信息的map
	 * @param xAix x坐标
	 * @param days 开始时间与结束时间之差
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年8月26日
	 * @see
	 */
	private int[] getYAxis(Map<String, List<OrderInfo>> m,String[] xAix,Integer days){
		int[] yAix = new int[days];
		for(int i = 0; i < xAix.length; i ++){
			if(m.get(xAix[i]) == null){
				yAix[i] = 0;
			} else {
				yAix[i] = m.get(xAix[i]).size();
			}
		}
		return yAix;
	}
	
	/**
	 * 
	 * @Description 按月显示已完成和已取消订单数<br>
	 * 
	 * @param seType 选择类型：1、固定搜索，年度，2、自由搜索
	 * @param monthSum 开始时间和结束时间间隔月数
	 * @param beginDate 开始时间
	 * @param endDate 结束时间
	 * @return 
	 * @author lilan 1063972142@qq.com
	 * @date 2016年8月29日
	 * @see
	 */
	@RequestMapping(value="orderMonthEchartsShow" , method = RequestMethod.POST)
	@ResponseBody
	public RequestJson orderMonthEchartsShow(Integer secType,Integer monthSum,String beginDate,String endDate,HttpServletRequest req){
		RequestJson result = new RequestJson();
		ShopInfo shopInfo = (ShopInfo)req.getSession().getAttribute(RequestConstants.SHOP_ID);
		
		try {
			List<OrderInfo> completedOrders = new ArrayList<OrderInfo>();
			List<OrderInfo> canceledOrders = new ArrayList<OrderInfo>();
			List<Object> list = new ArrayList<Object>();
			Map<String, Integer> mapOne = new HashMap<>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
			String[] xAix = new String[monthSum];
			String shopId = shopInfo.getId();

			completedOrders = orderInfoService.searchCompletedOrderByMonth(secType,beginDate,endDate,shopId);
			canceledOrders = orderInfoService.searchCanceledOrderByMonth(secType,beginDate,endDate,shopId);
			if(Constants.SEARCH_FIXED == secType){
				Date currentTime =DateUtils.str2Date(DateUtils.getCurrentTime(), sdf); // yyyy/MM
				Calendar rightNow = DateUtils.getCalendar();
				xAix = getXAxis(currentTime,rightNow,sdf ,Calendar.MONTH,xAix,monthSum);

			} else if(Constants.SEARCH_FREE == secType){

				Date endTime =DateUtils.str2Date(endDate, sdf); // yyyy/MM/dd
				Calendar end = DateUtils.getCalendar();
				xAix = getXAxis(endTime,end,sdf ,Calendar.MONTH,xAix,monthSum);

			}

			for(OrderInfo order:completedOrders){
				String formatTime = sdf.format(DateUtils.stringToDate(order.getMonths(), "yyyyMM")); // yyyy/MM
				mapOne.put(formatTime, order.getCount());

			}

			int[] yAixOne = new int[monthSum];
			for(int i = 0; i < xAix.length; i ++){
				if(mapOne.get(xAix[i]) == null){
					yAixOne[i] = 0;
				} else {
					yAixOne[i] = mapOne.get(xAix[i]);
				}
			}

			Map<String, Integer> mapTwo = new HashMap<>();
			for(OrderInfo order:canceledOrders){
				String formatTime = sdf.format(DateUtils.stringToDate(order.getMonths(), "yyyyMM")); // yyyy/MM/dd
				mapTwo.put(formatTime, order.getCount());
			}

			int[] yAixTwo = new int[monthSum];
			for(int i = 0; i < xAix.length; i ++){
				if(mapTwo.get(xAix[i]) == null){
					yAixTwo[i] = 0;
				} else {
					yAixTwo[i] = mapTwo.get(xAix[i]);
				}
			}

			Map mOne = new HashMap();
			mOne.put(xAix, yAixOne);
			Map mTwo = new HashMap();
			mTwo.put(xAix, yAixTwo);

			list.add(mOne.keySet());
			list.add(mOne.values());
			list.add(mTwo.values());

			result.setObj(list);
			result.setSuccess(true);

		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
		}
		return result;
	}
}
